package com.fay.designPattern.pattern.create.singleton.u43;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Title:
 * @Description:
 * @Author Fay Wang
 * @Date 2022/4/9 12:00
 * @Version 1.0
 */
public class IdGenerator {
    private AtomicLong id = new AtomicLong(0);

    private static final ConcurrentHashMap<Long, IdGenerator> instances = new ConcurrentHashMap<>();

    private IdGenerator() {

    }

    public static IdGenerator getInstance() {
        Long currentThread = Thread.currentThread().getId();
        instances.putIfAbsent(currentThread, new IdGenerator());
        return instances.get(currentThread);
    }

    public long getId() {
        return id.incrementAndGet();
    }

    public static void main(String[] args) throws InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(20);
        for (int i = 0; i < 20; i++) {
            Thread thread = new Thread(new Workout(cyclicBarrier));
            thread.setName("线程-" + (i + 1));
            thread.start();
        }
    }
}


class Workout implements Runnable {

    private final CyclicBarrier cyclicBarrier;

    public Workout(CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        try {
            cyclicBarrier.await();
            IdGenerator instance = IdGenerator.getInstance();
            System.out.println("线程id:"+instance.getId() + " ,对象为： " + instance);

        } catch (InterruptedException | BrokenBarrierException e1) {
            e1.printStackTrace();
        }
    }

}
